﻿using System;
using System.Text;

namespace UtilZ.Dotnet.Ex.Model
{
    /// <summary>
    /// 字符串文本数据源扩展类
    /// </summary>
    public class TextDataSource : IDataSourceExtend
    {
        private readonly bool _type;
        /// <summary>
        /// true:string;false:StringBuilder
        /// </summary>
        public bool Type
        {
            get { return this._type; }
        }

        private readonly string _text = null;
        /// <summary>
        /// 字符串文本
        /// </summary>
        public string Text
        {
            get { return this._text; }
        }

        private readonly StringBuilder _builder = null;
        /// <summary>
        /// 字符串文本
        /// </summary>
        public StringBuilder Builder
        {
            get { return this._builder; }
        }

        private readonly byte[] _data = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="text">字符串文本</param>
        public TextDataSource(string text)
        {
            this._text = text;
            this._type = true;
            this._data = Encoding.UTF8.GetBytes(text);
        }

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="builder">字符串文本</param>
        public TextDataSource(StringBuilder builder)
        {
            this._builder = builder;
            this._type = false;
            this._data = Encoding.UTF8.GetBytes(builder.ToString());
        }


        /// <summary>
        /// 数据长度字节数
        /// </summary>
        public int Length
        {
            get
            {
                return this._data.Length;
            }
        }

        /// <summary>
        /// 读取数据到buffer中
        /// </summary>
        /// <param name="buffer">数据缓存</param>
        /// <param name="offset">存储数据起始索引</param>
        /// <param name="count">读取数据长度</param>
        /// <param name="readOffset">数据源读取数据起始位置</param>
        public void Read(byte[] buffer, int offset, int count, int readOffset)
        {
            Array.Copy(this._data, readOffset, buffer, offset, count);
        }

        /// <summary>
        /// 将数据写到buffer中
        /// </summary>
        /// <param name="buffer">数据缓存</param>
        /// <param name="offset">存储数据起始索引</param>
        /// <param name="count">写入数据长度</param>
        /// <param name="writeOffset">数据源写入数据起始位置</param>
        public void Write(byte[] buffer, int offset, int count, int writeOffset)
        {
            Array.Copy(buffer, offset, this._data, writeOffset, count);
        }

    }

}
